//
//  TempletViewController.m
//  FruitsWholesaler
//
//  Created by sgone-2 on 15/11/17.
//  Copyright © 2015年 sgone. All rights reserved.
//

#import "TempletViewController.h"
#import "AFNetworking.h"
#import "DetailMoBanViewController.h"
#import "MBProgressHUD+MJ.h"

@interface TempletViewController ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;


@property (weak, nonatomic) IBOutlet UIButton *btnDaoru;






@property (nonatomic, strong) UIButton *startButton;
@property (nonatomic, strong) UIButton *stopButton;
//设置另一个全部取消按钮
@property (nonatomic, strong)  UIButton *quxiaoBtn;

@property(nonatomic,strong) NSMutableArray *list;

//设定bool标示
@property(strong,nonatomic) NSMutableArray* boolArray;
//重新获得新的数组,里面判断勾选的状态
@property(nonatomic,strong) NSMutableArray *dataArray;


//网路请求
@property(nonatomic,strong)AFHTTPSessionManager *manager;

@end

@implementation TempletViewController


//隐藏tabbar
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
        
    }
    return self;
}



//afnetworking网络请求数据
- (AFHTTPSessionManager *)manager
{
    if (_manager == nil) {
        _manager  = [AFHTTPSessionManager manager];
    }
    return _manager;
    
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.list = [NSMutableArray arrayWithCapacity:0];
    self.dataArray = [NSMutableArray arrayWithCapacity:0];
    
    
    self.backBtn.hidden = NO;
    self.titleLabel.text = @"模板导入";
    
    
    self.rightBut.hidden = NO;
    self.rightBut.frame = CGRectMake(ViewWidth *0.76, 20, 74, 44);
    self.rightBut.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.rightBut setTitle:@"全部选取" forState:UIControlStateNormal];
    
    
    
    self.btnDaoru.backgroundColor = BenSe_COLOR;
    self.btnDaoru.tintColor = [UIColor whiteColor];
    [self.btnDaoru setTitle:@"一  键  导  入" forState:UIControlStateNormal];
    [self.btnDaoru addTarget:self action:@selector(daoRu:) forControlEvents:UIControlEventTouchUpInside];
    
    

    
    
    [self sendAPI];
    


    
    
    
    
    
    
}







#pragma mark全部选择操作

- (void)rightButClick:(UIButton *)sender {
    
    if (!sender.tag) {
        
        [sender setTitle:@"全部取消" forState:UIControlStateNormal];
        for (int i = 0 ; i < self.boolArray.count; i++) {
            
            
            [self.boolArray replaceObjectAtIndex:i withObject:@"YES"];
        }
        [self.tableView reloadData];
        sender.tag = 1;
        
    }
    else
    {
    
        [sender setTitle:@"全部选取" forState:UIControlStateNormal];
        for (int i = 0; i < self.boolArray.count; i++) {
            
            [self.boolArray replaceObjectAtIndex:i withObject:@"NO"];
            
        }
    
        [self.tableView reloadData];
        sender.tag = 0 ;
        
    
    }
    
    
}


#pragma mark导入全部数据
-(void)daoRu:(UIButton *)sender
{
    
    NSString* goodsID = @"";
    //将数据进行导入
    for (int i = 0; i < self.boolArray.count; i++)
    {
        NSString *boolStr = self.boolArray[i];
        if ([boolStr isEqualToString:@"YES"]) {
            
            NSDictionary *dic = [self.list objectAtIndex:i];
            NSString * ID = [dic valueForKey:@"product_id"];
            if (!i)
            {
                
                goodsID = [NSString stringWithFormat:@"%@",ID];
                
            }
            else
            {
                goodsID = [NSString stringWithFormat:@"%@,%@",goodsID,ID];
          
            }
        }
    }
    
    
    //如果没有进行选择
    if (goodsID.length == 0) {
        
        UIAlertView *alter  = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请选择商品" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];
        
        return;
    }
    
    //上传productID到服务器
    NSString *urlStr = [NSString stringWithFormat:@"%@import_product_template",SERVER_ADDRESS2];
    NSDictionary *params =@{@"wTel" : self.dataHandler.phone , @"uToken" : self.dataHandler.uToken , @"product_id" : goodsID}
    ;
    
    [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
    [self.manager POST:urlStr parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([responseObject[@"error_flag"] intValue] == 0) {
            
            
            [MBProgressHUD hideAllHUDsForView:self.tableView animated:YES];
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"上传成功!" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];
            
            
            //发起通知告知前一个页面进行从新获取网络信息,进行页面刷新
            
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"muban" object:nil];
            
            
            
            
            
            
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [MBProgressHUD hideAllHUDsForView:self.tableView animated:YES];

            NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
            
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];
        }
        
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [MBProgressHUD hideAllHUDsForView:self.tableView animated:YES];
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请检查网络" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];
    }];

}






#pragma mark 获取网络数据
-(void)sendAPI
{

    NSString *urlStr = [NSString stringWithFormat:@"%@/product_template",SERVER_ADDRESS2];

    NSDictionary *params = @{@"wTel" : self.dataHandler.phone , @"uToken" : self.dataHandler.uToken};

    
    [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
    [self.manager POST:urlStr parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([responseObject[@"error_flag"] intValue] == 0) {
    
            
//            NSLog(@"获取得到的最新数据 %@",responseObject[@"data"][@"product_template"] );
            if (![responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                
                [MBProgressHUD hideAllHUDsForView:self.tableView animated:YES];
                return ;
            }
            else
            {
        
                NSArray *array = responseObject[@"data"][@"product_template"];
                
                self.list = [array copy];
            
            }
          
            
            self.boolArray = [[NSMutableArray alloc]initWithCapacity:0];
            for (int i = 0; i < self.list.count; i++) {
                
                [self.boolArray addObject:@"NO"];
            }
            
            [MBProgressHUD hideAllHUDsForView:self.tableView animated:YES];

            [self.tableView reloadData];
            
        }
        
        else
        {
        
             [MBProgressHUD hideAllHUDsForView:self.tableView animated:YES];
            NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
            
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];
        
        }
        
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.tableView animated:YES];

        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请检查网络" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];
        
    }];





}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 1;

}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return self.list.count;


}



-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

    return 0.001;

}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{

    return 0.001;

}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return 100;


}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

  static NSString *CellIdentifier = @"Cell";
    
    TempletCell  *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        cell = [[NSBundle mainBundle]loadNibNamed:@"TempletCell" owner:self options:nil][0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        
        cell.delegate = self;
        
        
    }
 
    
    
    
    //单选与多选 的操作
    cell.btnGou.tag = indexPath.row;
    [cell.btnGou addTarget:self action:@selector(btnGouA:) forControlEvents:UIControlEventTouchUpInside];
    
    //勾选与未勾选进行操作,图片操作
    if ([self.boolArray [indexPath.row] isEqualToString:@"YES"]) {
        [[cell imageGou] setImage:[UIImage imageNamed:@"gou2"]];
        
        
    }
    
    else
    {
    
        [[cell imageGou] setImage:[UIImage imageNamed:@"gou1"]];
    
    }
    
    NSDictionary *dict = [self.list objectAtIndex:indexPath.row];
    [cell loadCell:dict];
    
    return cell;


}



//点击cell进入下一个页面显示详情

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSInteger row = [indexPath row];
    NSDictionary *dic = [self.list objectAtIndex:row];
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    
    DetailMoBanViewController *detailMB = [[DetailMoBanViewController alloc]initWithNibName:nil bundle:nil];
    
    detailMB.detailDic = [NSMutableDictionary dictionaryWithDictionary:dic];
    
    
    
    [self.navigationController pushViewController:detailMB animated:YES];
    



}





#pragma mark 设定勾选的按钮操作,单选多选

-(void)btnGouA:(UIButton *)sender
{

    
//    NSLog(@"我被摸了");
    NSString * str = self.boolArray[sender.tag];
    if ([str isEqualToString:@"YES"]) {
        
        [self.boolArray replaceObjectAtIndex:sender.tag withObject:@"NO"];
       
        
        
        
        NSArray *array = [NSArray arrayWithArray:self.dataArray];
        
        
        for (NSDictionary *dic in  array)
        {
        
            if ([[self.list[sender.tag] objectForKey:@"product_id"] isEqualToString:[dic objectForKey:@"product_id"]]) {
                
                [self.dataArray removeObject:dic];
                
                
            }
        
        
        
        }
        
    }

    else
    {
    
    
        [self.boolArray replaceObjectAtIndex:sender.tag withObject:@"YES"];
        
        
        //将这些数据加入到数组中
        [self.dataArray addObject:self.list[sender.tag]];
        
    
    
    }

    
    //打印出勾选的名字
    
//    for (NSDictionary *dict in  self.dataArray)
//    {
//    
////        NSLog(@"_------> , %@",[dict objectForKey:@"product_name"]);
//    
//    }
//    
    
    [self.tableView reloadData];
    
}


@end
